const app = getApp();
const db = wx.cloud.database()
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    bookinfo: {}
  },

  http: function(isbn) {
    wx.cloud.callFunction({
      name: 'dangdang',
      data: {
        isbn: isbn
      }
    }).then(res => {
      console.log(res.result)
      this.setData({
        bookinfo: res.result
      })
    })
  },

  scanbook: function() {
    wx.scanCode({
      success: res => {
        console.log(res)
        this.http(res.result)
      }
    })
  },

  search: function() {
    var isbn = this.data.bookinfo.ISBN
    this.http(isbn)
  },

  showImg() {
    wx.previewImage({
      urls: [this.data.bookinfo.url],
      current: this.data.bookinfo.url // 当前显示图片的http链接      
    })
  },

  updateValue: function(event) {
    let name = event.currentTarget.dataset.name;
    let bookinfo = this.data.bookinfo
    bookinfo[name] = event.detail.value
    this.setData({
      bookinfo: bookinfo
    })
  },

  updateprice: function(event) {
    event.detail.value = event.detail.value.replace(/^([1-9]\d{0,2}(\.[\d]{0,2})?|0(\.[\d]{0,2})?)[\d.]*/g, '$1'); //金额校验
    let name = event.currentTarget.dataset.name;
    let bookinfo = this.data.bookinfo
    bookinfo[name] = event.detail.value
    this.setData({
      bookinfo: bookinfo
    })
  },

  submitform: function(event) {
    let bookinfo = this.data.bookinfo
    var reg = /(^[1-9]\d{0,2}(\.[\d]{1,2})?$)|(^(0){1}$)|(0(\.[\d]{1,2})?$)/;
    if (!reg.test(bookinfo.saleprice) || !reg.test(bookinfo.price)) {
      console.log("error....")
      wx.showToast({
        title: "请输入正确的金额",
        icon: 'none',
        duration: 1000
      })
      return
    }
    bookinfo.saleprice = parseFloat(bookinfo.saleprice)
    bookinfo.定价 = parseFloat(bookinfo.price)
    db.collection('book').add({
        data: bookinfo,
      })
      .then(res => {
        console.log(res)
        wx.showToast({
          title: '添加成功...',
          icon: 'none',
          duration: 1500
        })
        wx.navigateTo({
          url: '../home/home'
        });
      })
      .catch(console.error)
  }
})